package com.tjk.luckymoney.controller;

import com.tjk.luckymoney.domain.Luckymoney;
import com.tjk.luckymoney.repository.LuckymoneyRepository;
import com.tjk.luckymoney.service.LuckymoneyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@RestController
public class LuckymoneyController {

    @Autowired
    private LuckymoneyRepository repository;
    @Autowired
    private LuckymoneyService service;

    /**
     *  获取红包列表
     */
    @GetMapping("/luckymoneys")
    public List<Luckymoney> list() {
        return repository.findAll();
    }

    /**
     *  创建红包
     */
    @GetMapping("/saveLuckymoney")
    public Luckymoney create(@RequestParam("money") BigDecimal money,
                             @RequestParam("producer") String producer) {
        Luckymoney luckymoney = new Luckymoney();
        luckymoney.setProducer(producer);
        luckymoney.setMoney(money);
        return repository.save(luckymoney);
    }

    /**
     *  通过id查询红包
     */
    @GetMapping("/luckymoneys/{id}")
    public Luckymoney findById(@PathVariable("id") Integer id) {
        repository.findById(id);
        return repository.findById(id).orElse(null);
    }

    /**
     *  更新红包（领红包）
     */
    @GetMapping("/updateLuckymoney/{id}")
    public Luckymoney update(@PathVariable("id") Integer id,
                             @RequestParam("consumer") String consumer) {
        Optional<Luckymoney> luckymoneys = repository.findById(id);
        if (luckymoneys.isPresent()) {
            Luckymoney luckymoney = luckymoneys.get();
            luckymoney.setConsumer(consumer);
            return repository.save(luckymoney);
        }
        return null;
    }

    @PostMapping("/luckymoneys/createTwo")
    public void createTwo() {
        service.createTwo();
    }
}
